﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc.Ajax;
using System.Globalization;

namespace MvcEngine.Mvc.Extensions
{
    public static class AjaxOptionsExtensions
    {
        public static string ToJavascriptString(this AjaxOptions options)
        {
            StringBuilder builder = new StringBuilder("{");
            builder.Append(string.Format(CultureInfo.InvariantCulture, " insertionMode: {0},", new object[] { InsertionModeToString(options.InsertionMode) }));
            builder.Append(PropertyStringIfSpecified("confirm", options.Confirm));
            builder.Append(PropertyStringIfSpecified("httpMethod", options.HttpMethod));
            builder.Append(PropertyStringIfSpecified("loadingElementId", options.LoadingElementId));
            builder.Append(PropertyStringIfSpecified("updateTargetId", options.UpdateTargetId));
            builder.Append(PropertyStringIfSpecified("url", options.Url));
            builder.Append(EventStringIfSpecified("onBegin", options.OnBegin));
            builder.Append(EventStringIfSpecified("onComplete", options.OnComplete));
            builder.Append(EventStringIfSpecified("onFailure", options.OnFailure));
            builder.Append(EventStringIfSpecified("onSuccess", options.OnSuccess));
            builder.Length--;
            builder.Append(" }");
            return builder.ToString();
        }

        private static string PropertyStringIfSpecified(string propertyName, string propertyValue)
        {
            if (!string.IsNullOrEmpty(propertyValue))
            {
                string str = propertyValue.Replace("'", @"\'");
                return string.Format(CultureInfo.InvariantCulture, " {0}: '{1}',", new object[] { propertyName, str });
            }
            return string.Empty;
        }

        private static string EventStringIfSpecified(string propertyName, string handler)
        {
            if (!string.IsNullOrEmpty(handler))
            {
                return string.Format(CultureInfo.InvariantCulture, " {0}: Function.createDelegate(this, {1}),", new object[] { propertyName, handler.ToString() });
            }
            return string.Empty;
        }

        internal static string InsertionModeToString(InsertionMode insertionMode)
        {
            switch (insertionMode)
            {
                case InsertionMode.Replace:
                    return "Sys.Mvc.InsertionMode.replace";

                case InsertionMode.InsertBefore:
                    return "Sys.Mvc.InsertionMode.insertBefore";

                case InsertionMode.InsertAfter:
                    return "Sys.Mvc.InsertionMode.insertAfter";
            }
            int num = (int)insertionMode;
            return num.ToString(CultureInfo.InvariantCulture);
        }
    }
}
